package edu.whut.mall;

import edu.whut.mall.codegenerator.utils.DBUtil;
import edu.whut.mall.codegenerator.utils.Field;
import edu.whut.mall.codegenerator.utils.FreeMakerUtil;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @program: wayne
 * @description: 代码生成器
 * @author: Wayne
 * @create: 2020-03-16 15:25
 **/
public class Generator {

    static String ADMINMODULE = "admin";
    static String PORTALMODULE = "portal";
    static String CommonPrefix = "\\src\\main\\java\\edu\\whut\\mall\\";
    static String SERVICEPATH = "\\service\\impl\\";
    static String ISERVICEPATH = "\\service\\";
    static String generatorConfigPath = "pojo\\src\\main\\resources\\generatorConfig.xml";
    static String CONTROLLERPATH = "\\controller\\";
    static String PARAMSPATH = "/domain/";
    static String VOPATH = "/vo/";
    static String AUTHOR = "Wayne";

    public static void main(String[] args) throws Exception {
        generatorPOJO();
//        generatorOther(PORTALMODULE, "支付信息");

}

    private static void generatorPOJO() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        //MBG 执行过程中的警告信息
        List<String> warnings = new ArrayList<String>();
        //当生成的代码重复时，覆盖原代码
        boolean overwrite = true;
        //读取我们的 MBG 配置文件
        InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(is);
        is.close();

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        //创建 MBG
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        //执行生成代码
        myBatisGenerator.generate(null);
        //输出警告信息
        for (String warning : warnings) {
            System.out.println(warning);
        }
    }

    private static void generatorOther(String moduleName, String myComment) throws Exception{

        // 只生成配置文件中的第一个table节点
        File file = new File(generatorConfigPath);
        SAXReader reader=new SAXReader();
        //读取xml文件到Document中
        Document doc=reader.read(file);
        //获取xml文件的根节点
        Element rootElement=doc.getRootElement();
        //读取context节点
        Element contextElement = rootElement.element("context");
        //定义一个Element用于遍历
        Element tableElement;
        //取第一个“table”的节点
        tableElement=contextElement.elementIterator("table").next();
        String Domain = tableElement.attributeValue("domainObjectName");
        String tableName = tableElement.attributeValue("tableName");
        String domain = Domain.substring(0, 1).toLowerCase() + Domain.substring(1);
        System.out.println("表："+tableElement.attributeValue("tableName"));
        System.out.println("Domain："+tableElement.attributeValue("domainObjectName"));

        List<Field> fieldList = DBUtil.getColumnByTableName(tableName);
        Set<String> typeSet = getJavaTypes(fieldList);
        Map<String, Object> map = new HashMap<>();
        map.put("ClassName", Domain);
        map.put("className", domain);
        map.put("Module", moduleName);
        map.put("myComment", myComment);
        map.put("fieldList", fieldList);
        map.put("typeSet", typeSet);
        map.put("author", AUTHOR);
        map.put("date", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        // 生成Params
        FreeMakerUtil.initConfig("params.ftl");
        FreeMakerUtil.generator(moduleName + CommonPrefix + moduleName + PARAMSPATH + Domain + "Params.java", map);

        // 生成vo
        FreeMakerUtil.initConfig("vo.ftl");
        FreeMakerUtil.generator(moduleName + CommonPrefix + moduleName + PARAMSPATH + Domain + "Vo.java", map);

        // 生成service
        FreeMakerUtil.initConfig("service.ftl");
        FreeMakerUtil.generator( moduleName + CommonPrefix + moduleName + SERVICEPATH + Domain + "ServiceImpl.java", map);

        // 生成Iservice
        FreeMakerUtil.initConfig("Iservice.ftl");
        FreeMakerUtil.generator(moduleName + CommonPrefix + moduleName + ISERVICEPATH + "I" + Domain + "Service.java", map);

        // 生成controller
        FreeMakerUtil.initConfig("controller.ftl");
        FreeMakerUtil.generator(moduleName + CommonPrefix + moduleName + CONTROLLERPATH + "Rest" + Domain + "Controller.java", map);
    }



    /**
     * 获取所有的Java类型，使用Set去重
     */
    private static Set<String> getJavaTypes(List<Field> fieldList) {
        Set<String> set = new HashSet<>();
        for (int i = 0; i < fieldList.size(); i++) {
            Field field = fieldList.get(i);
            set.add(field.getJavaType());
        }
        return set;
    }
}
